<template>
  <el-dialog :title="title" width="800px" append-to-body :visible.sync="dialogedit" @open="openDialog"
    :before-close="closeDialog" :close-on-click-modal="false">
    <div class="form-box">
      <el-form ref="formdata" :model="ruleform" :rules="rules" label-suffix="：" :validate-on-rule-change="false"
        :show-message="false" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="dept_id">
              <treeselect v-model="ruleform.dept_id" :options="deptOptions" :show-count="true" :normalizer="normalizer"
                placeholder="请选择归属部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="user_name">
              <el-input v-model="ruleform.user_name" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nick_name">
              <el-input v-model="ruleform.nick_name" placeholder="请输入用户昵称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="ruleform.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password
                :disabled="user_id!=='' " />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="ruleform.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>

          <!-- <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleform.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="ruleform.sex" placeholder="请选择性别" style="width: 100%;">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="12">
            <el-form-item label="岗位">
              <el-select v-model="ruleform.post_ids" multiple placeholder="请选择岗位" style="width: 100%;">
                <el-option v-for="item in postOptions" :key="item.post_id" :label="item.post_name"
                  :value="item.post_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="角色">
              <el-select v-model="ruleform.role_ids" multiple placeholder="请选择角色" style="width: 100%;">
                <el-option v-for="item in roleOptions" :key="item.role_id" :label="item.role_name"
                  :value="item.role_id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="ruleform.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="ruleform.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value"
                  :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row v-if="ruleform.user_id !== undefined">
          <el-col :span="24">
             <el-checkbox v-model="resetpwd">初始密码</el-checkbox>
          </el-col>
        </el-row> -->
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="save_validate()">保 存</el-button>
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import {
    getConfigKey
  } from '@/api/system/config';
  import {
    getPostOption
  } from '@/api/system/post';
  import {
    getRoleOption
  } from '@/api/system/role';
  import {
    saveUser,
    Get_Info
  } from '@/api/system/user';

  import {
    listDept
  } from '@/api/system/dept';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
    name: 'user_edit',
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: {
      Treeselect
    },
    props: {
      dialogedit: {
        type: Boolean,
        default: false
      },
      user_id: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        title: '修改用户',
        ruleform: {
          user_id: '',
          dept_id: null,
          user_name: '',
          nick_name: '',
          email: '',
          phonenumber: '',
          sex: '',
          password: '',
          status: '',
          remark: '',
          post_ids: [],
          role_ids: []
        },
        rules: {
          dept_id: [{
            required: true,
            message: '部门不能为空'
          }],
          nick_name: [{
            required: true,
            message: '用户昵称不能为空'
          }],
          user_name: [{
            required: true,
            message: '用户名称不能为空'
          }],
          status: [{
            required: true,
            message: '状态不能为空'
          }]
        },
        deptOptions: [],
        postOptions: [],
        roleOptions: [],
        glbm_options: [],
        initPassword: '',
        resetpwd: false
      };
    },
    created() {
      this.get_options()
    },
    methods: {
      /** 获取岗位及角色 */
      get_options() {
        getPostOption().then(response => {
          this.postOptions = response.rows;
        });
        getRoleOption().then(response => {
          this.roleOptions = response.rows;
        });
        getConfigKey("sys.user.initPassword").then(response => {
          this.initPassword = response.initPassword;
        });
        listDept({}).then(response => {
          this.deptOptions = this.handleTree(response.rows, "dept_id", "parent_id");
        });
      },
      /** 转换部门数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.dept_id,
          label: node.dept_name,
          children: node.children
        };
      },
      closeDialog() {
        this.$nextTick(() => {
          this.$refs.formdata.resetFields();
          this.$emit('update:dialogedit', !this.dialogedit);
        });
      },
      save_validate() {
        this.$refs.formdata.validate((valid, valids) => {
          if (valid) {
            this.save_user();
          } else {
            var msg = '';
            for (var key in valids) {
              var item = valids[key];
              msg = item[0].message;
              break;
            }
            if (msg) this.$message.error(msg);

            return false;
          }
        });
      },

      async save_user() {
        const loading = this.loading('保存中...');
        const params = {
          user_id: this.ruleform.user_id == undefined ? '0' : this.ruleform.user_id,
          dept_id: this.ruleform.dept_id == undefined ? '0' : this.ruleform.dept_id,
          user_name: this.ruleform.user_name == undefined ? '' : this.ruleform.user_name,
          nick_name: this.ruleform.nick_name == undefined ? '' : this.ruleform.nick_name,
          email: this.ruleform.email == undefined ? '' : this.ruleform.email,
          phonenumber: this.ruleform.phonenumber == undefined ? '' : this.ruleform.phonenumber,
          sex: this.ruleform.sex == undefined ? '' : this.ruleform.sex,
          password: this.ruleform.password == undefined ? '' : this.ruleform.password,
          status: this.ruleform.status == undefined ? '' : this.ruleform.status,
          remark: this.ruleform.remark == undefined ? '' : this.ruleform.remark,
          post_ids: this.ruleform.post_ids ? this.ruleform.post_ids.join(",") : "",
          role_ids: this.ruleform.role_ids ? this.ruleform.role_ids.join(",") : "",
          glbm: this.ruleform.glbm == undefined ? '' : this.ruleform.glbm,
        }

        saveUser(params).then(response => {
          this.$modal.msgSuccess("保存成功");
          loading.close();
          this.closeDialog();
          this.$emit('reload');
        }).catch(err => {
          loading.close();
        });
      },

      getinfo() {
        const Parmas = {
          user_id: this.user_id
        }

        Get_Info(Parmas).then(res => {
          const data = res.data;

          this.ruleform = {
            user_id: data.user_id,
            dept_id: data.dept_id,
            user_name: data.user_name,
            nick_name: data.nick_name,
            email: data.email,
            password: data.password,
            phonenumber: data.phonenumber,
            sex: data.sex,
            status: data.status,
            remark: data.remark,
            post_ids: data.post_ids,
            role_ids: data.role_ids
          }
          console.log(this.ruleform);
        }).catch(err => {

        });
      },
      async openDialog() {

        if (this.user_id) {
          this.title = "修改用户";
          this.getinfo();
        } else {
          this.title = "新增用户";
          this.ruleform= {
            user_id: '',
            dept_id: null,
            user_name: '',
            nick_name: '',
            email: '',
            phonenumber: '',
            sex: '',
            password: '',
            status: '',
            remark: '',
            post_ids: [],
            role_ids: []
          };
          this.ruleform.password = this.initPassword;
        }
      }
    }
  };
</script>

<style scoped>
  .form-box {
    min-height: 60px;
    padding-right: 10px;
    overflow: auto;
  }
</style>
